package a66weding.com.jiehuntong.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.common.utils.x5Util.X5WebView;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;

/**
 * 请柬主题预览界面
 */
public class PreviewThemeActivity extends BaseHomeActivity implements OnNetResultListener, View.OnClickListener {
    private X5WebView preview_webview;
    private WebSettings settings;
    private Button buttonUse;
    private int tid;
    private int useId;
    private boolean isSeted = false;
    private ImageView exitPreview;
    private String tempUrl;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_preview_theme);
        tid = getIntent().getIntExtra("tid", -1);
        useId = getIntent().getIntExtra("useId", -2);
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==8000&&resultCode==LoginActivity.LOGIN_OK){
            if (tid != useId) {
                //buttonUse.setEnabled(false);
                int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
                HttpRequestBean httpRequestBean = new HttpRequestBean();
                // 设置使用模板
                httpRequestBean.setListener(this);
                httpRequestBean.setClazz(SimpleBean.class);
                httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
                httpRequestBean.setUrl(RequestCode.SURL + RequestCode.UPMARRYCARDTEMPLATE + "&uid=" + uId + "&tid=" + tid);
                HttpHandleUtil.executeCommonPost(this, httpRequestBean);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (preview_webview != null) {
            preview_webview.loadUrl("javascript:autoPlayMusic(" + "true" + ")");
        }
    }

    private void initView() {
        preview_webview = (X5WebView) findViewById(R.id.x5_webview);
        exitPreview = (ImageView) findViewById(R.id.img_exit_preview);
        exitPreview.setOnClickListener(this);
        buttonUse = (Button) findViewById(R.id.btn_use_previewtheme);
        tempUrl = getIntent().getStringExtra("TempUrl");
        settings = preview_webview.getSettings();
        // 支持javascript
        settings.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        // 不显示缩放按钮
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        // 自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        // 不使用缓存，只从网络获取数据
        preview_webview.loadUrl(tempUrl);
        if (Utils.checkNet(this)) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

        preview_webview.setWebViewClient(new WebViewClient() {// 回调网页加载的生命周期
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isForeground(PreviewThemeActivity.this, "PreviewThemeActivity")) {
                    preview_webview.loadUrl("javascript:autoPlayMusic(" + "true" + ")");
                } else {
                    preview_webview.loadUrl("javascript:autoPlayMusic(" + "false" + ")");
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http") || url.startsWith("https")) {
                    if (url.contains("http://api.map.baidu.com")) {
                        Intent intent = new Intent(PreviewThemeActivity.this, WebViewActvity.class);
                        intent.putExtra("urlPath", url);
                        intent.putExtra("title", "婚礼举办地");
                        intent.putExtra("share", false);
                        PreviewThemeActivity.this.startActivity(intent);
                        return true;
                    }
                    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                    view.loadUrl(url);
                    return true;
                } else if (url.startsWith("tel:")) {
                    if (!url.replace("tel:", "").equals("")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
        });
        if (useId == tid) {
            // buttonUse.setEnabled(false);
            buttonUse.setText("当前主题");
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName().substring(cpn.getClassName().lastIndexOf(".") + 1, cpn.getClassName().length()))) {
                return true;
            }
        }
        return false;
    }

    public void useTheme(View view) {
        if (((GlobalApplication) this.getApplication()).isLogin()) {
            if (tid != useId) {
                //buttonUse.setEnabled(false);
                int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
                HttpRequestBean httpRequestBean = new HttpRequestBean();
                // 设置使用模板
                httpRequestBean.setListener(this);
                httpRequestBean.setClazz(SimpleBean.class);
                httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
                httpRequestBean.setUrl(RequestCode.SURL + RequestCode.UPMARRYCARDTEMPLATE + "&uid=" + uId + "&tid=" + tid);
                HttpHandleUtil.executeCommonPost(this, httpRequestBean);
            } else {
                Intent intent = new Intent(PreviewThemeActivity.this, ElectronicInvitationActivity.class);
                startActivity(intent);
                finish();
            }
        } else {
            showLoginDialog(this, "亲，需要登录哦~", "去登录", "取消");
        }
    }
    public  void showLoginDialog(final Context context, String title, String confirm, String cancel) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, title, confirm, cancel,R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(PreviewThemeActivity.this, LoginActivity.class);
                PreviewThemeActivity.this.startActivityForResult(intent,8000);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (preview_webview != null) {
            preview_webview.loadUrl("javascript:autoPlayMusic(" + "false" + ")");
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        isSeted = true;
//        buttonUse.setEnabled(false);
        buttonUse.setText("当前主题");
        //通知我的电子请柬更新界面
        sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
        //通知来预览界面的界面更新当前使用的主题
        Intent intents = new Intent(ThemeSettingsActivity.ACTION_REFRESH_PREVIEWINVITATION);
        intents.putExtra("previewID", tid);
        sendBroadcast(intents);

        Intent intent = new Intent(PreviewThemeActivity.this, ElectronicInvitationActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("设置失败!请稍后重试!");
        buttonUse.setEnabled(true);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (preview_webview != null) {
            preview_webview.loadUrl("javascript:autoPlayMusic(" + "false" + ")");
            preview_webview.destroy();
        }
        Intent intent = new Intent();
        intent.putExtra("isSeted", isSeted);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_exit_preview:
                onBackPressed();
                break;
        }
    }

    /**
     * 设置应用字号不受系统字号设置的影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
